package com.uuuo.okhttp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okio.BufferedSource;
import okio.Okio;

public class MainActivity extends AppCompatActivity {

    OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void getRequest(View view) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://www.wanandroid.com/banner/json")
                .get()
                .build();

        Response response = client.newCall(request).execute();
        Log.i("res--->", response.body().string());

    }

    public void postRequest(View view) {
//        RequestBody formBody = new FormBody.Builder()
//                .add("", "")
//                .build();

        final Request request = new Request.Builder()
                .url("http://www.wooyun.org")
//                .post(formBody)
                .build();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.i("WY", "打印POST响应的数据：" + response.body().string());
                    } else {
                        throw new IOException("Unexpected code " + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void enqueue(View view) {
        Request request = new Request.Builder()
                .url("http://publicobject.com/helloworld.txt")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure---->" + Thread.currentThread().getName());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("onResponse---->" + Thread.currentThread().getName());
            }

        });
    }


    public void okio(View view) throws Exception {
        File file = new File("hello.txt");
        FileInputStream in = new FileInputStream(file);
        BufferedSource source = Okio.buffer(Okio.source(in));  //创建BufferedSource
        String s = source.readUtf8();  //以UTF-8读
        System.out.println(s);     //打印
        source.close();
    }
}
